<template>
  <ContentWrap>
    <div class="flex justify-between">
      <div class="">
        <ElButton type="primary" :icon="Plus" @click="onAdd">
          {{ t('新增') }}
        </ElButton>
      </div>
      <div class="">
        <ElInput v-model="state.searchData.searchValue" style="width: 266px;height: 32px;margin-right: 10px;"
          placeholder="用户名/手机号" :prefix-icon="Search" />
        <ElButton type="primary" :icon="Search" @click="onSearch">
          {{ t('common.query') }}
        </ElButton>
        <ElButton :icon="Refresh" @click="onReset">
          {{ t('common.reset') }}
        </ElButton>
      </div>
    </div>
    <!-- <div class="flex" style="margin-top: 25px;">
      <Asearch :data="state.schema" />
    </div> -->
    <div class="" style="margin-top: 25px;">
      <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
        :data="dataList" :loading="loading" :pagination="{ total: total }" @register="tableRegister"
        :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" />
    </div>
  </ContentWrap>
  <Dialog v-model="dialogVisible1" :title="state.dialogVisible1title" width="500">
    <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
      status-icon>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="state.ruleForm.nickName" placeholder="请输入用户昵称" />
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="state.ruleForm.userName" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input v-model="state.ruleForm.phonenumber" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="绑定角色" prop="roleIds">
        <el-select v-model="state.ruleForm.roleIds"  collapse-tags filterable multiple class="m-2" clearable placeholder="请选择角色">
          <el-option v-for="item in state.rolesData" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
        </el-select>
      </el-form-item>

      <el-form-item label="密码" prop="password" v-if="state.dialogVisible1title != '编辑用户'">
        <el-input v-model="state.ruleForm.password" show-password type="password" placeholder="请输入密码"
          :disabled="state.dialogVisible1title == '编辑用户'" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex ">
        <ElButton @click="resetForm(ruleFormRef)">{{ t('dialogDemo.cancel') }}</ElButton>
        <ElButton type="primary" :loading="btn_loading" @click="submitForm(ruleFormRef)">{{ t('dialogDemo.sure') }}
        </ElButton>
      </div>
    </template>
  </Dialog>
</template>
  
<script setup lang="tsx">
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Plus, Refresh, Pointer, Star } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useForm } from '@/hooks/web/useForm'
import { getUserListApi, addUserApi, editUserApi, deteleUserApi, getUserInfoApi } from "@/api/user/index"
import { getRoleOptionselectApi } from "@/api/roles/index"

const { formRegister, formMethods } = useForm()
const { getElFormExpose } = formMethods
const { t } = useI18n()
const dialogVisible1 = ref(false)
const state = reactive({
  dialogVisible1title: "新增用户",
  reactBoolean: false,//重置
  optionsTenantData: [] as any,
  optionsTypeData: [
    // {
    //     value: "sys_user",
    //     label: "管理端用户"
    // },
    {
      value: "enterprise_user",
      label: "企业端用户"
    },
    {
      value: "application_user",
      label: "应聘端用户"
    }
  ],
  searchData: {
    userType: "",
    searchValue: "",
    tenantId: ""
  },
  ruleForm: {} as any,
  react: false,
  rolesData: [] as any
})
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'userId',
    label: t('账号ID'),
    search: {
      component: 'Input'
    },
    form: {
      component: 'Input',
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'nickName',
    label: t('昵称'),
    search: {
      hidden: true
    }
  },
  {
    field: 'userName',
    label: t('用户名'),
    search: {
      hidden: true
    }
  },
  {
    field: 'phonenumber',
    label: t('手机号'),
    search: {
      hidden: true
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElButton link type="primary" onClick={() => action(data[0].row)}>
                {t('编辑')}
              </ElButton>
              {/* <ElButton link type="primary" onClick={() => receat(data[0].row)}>
                {t('查看')}
              </ElButton> */}
              <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                {t('删除')}
              </ElButton>

            </>
          )
        }
      }
    }
  }
])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res: any = await getUserListApi({
      pageNum: state.react ? 1 : unref(currentPage),
      pageSize: unref(pageSize),
      userType: "sys_user",
      searchValue: state.searchData.searchValue,
      tenantId: state.searchData.tenantId
    })
    console.log("用户：", res);
    state.react = false
    res.rows.forEach(elements => {
      if (elements.status == 0) {
        elements.statusBoolean = true
      } else {
        elements.statusBoolean = false
      }
      state.optionsTenantData.forEach(element => {
        if (elements.tenantId == element.value) {
          elements.tenantName = element.label
        }

      })
      state.optionsTypeData.forEach(element => {
        if (elements.userType == element.value) {
          elements.userTypeName = element.label
        }

      })
    })
    return {
      list: res.rows,
      total: res.total
    }
  }
})
// 表格头部信息
const headerCellStyle: any = {
  "background": "#F2F6FC",
  "height": "48px"
}
// 
const rowStyle: any = {
  "height": "48px"
}
const { loading, dataList, total, currentPage, pageSize } = tableState

const { getList, getElTableExpose, delList } = tableMethods

getList()
useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})
const { allSchemas } = useCrudSchemas(crudSchemas)
const action = (row: any) => {
  console.log("编辑", row);
  state.ruleForm=row
  // state.ruleForm.password = "123456"
  state.dialogVisible1title = t('编辑用户')
  getUserInfoApi_(row.userId)
}
const delData = (row: any) => {
  console.log("删除", row);
  ElMessageBox.confirm('确认删除该用户？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    // inputPattern:,
    draggable: true,
    type: 'warning',
  }).then(() => {
    deteleUserApi([row.userId]).then((res: any) => {
      getList()
      ElMessage({
        type: 'success',
        message: `${res.msg}`,
      })
    }).catch((res: any) => {
      ElMessage({
        type: 'error',
        message: `${res.msg}`,
      })
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消操作',
    })
  })

}

// 新增
const onAdd = () => {
  console.log("新增");
  state.ruleForm = {}
  dialogVisible1.value = true
  state.dialogVisible1title = t('新增用户')
}

// 查询
const onSearch = () => {
  console.log("查询");
  state.react = true
  getList()
}
// 重置
const onReset = () => {
  console.log("重置");
  state.searchData.searchValue = "";
  state.searchData.userType = "";
  state.searchData.tenantId = "";
  state.react = true
  getList()
}

// 表单
// 校验规则
interface RuleForm {
  name: string
  region: string
  count: string
  date1: string
  date2: string
  delivery: boolean
  roleIds: string[]
  resource: string
  desc: string
}


var checkData = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error("密码不能输入汉字!"));
    } else {
      callback();
    }
  }
  callback();
};
var checkDatas = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error("用户名不能输入汉字!"));
    } else {
      callback();
    }
  }
  callback();
};

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
  roleIds: [
    { type: "array", required: true, message: '请选择绑定角色', trigger: 'blur' },
  ],
  nickName: [
    { required: true, message: '请填写用户昵称', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
  ],
  userName: [
    { required: true, message: '请填写用户名', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    { validator: checkDatas, trigger: "blur" },
  ],
  phonenumber: [
    { required: true, message: '请填写手机号', trigger: 'blur' },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: '请填写密码', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    { validator: checkData, trigger: "blur" },
    // {
    //   required: true,
    //   pattern:
    //     /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,20}$/,
    //   message: "包含大小写字母、数字和特殊字符的三种",
    //   trigger: "blur",
    // }
  ]

})
const btn_loading = ref(false)
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (state.dialogVisible1title == '新增用户') {
        let obj = {
          "nickName": state.ruleForm.nickName,
          "userName": state.ruleForm.userName,
          "phonenumber": state.ruleForm.phonenumber,
          "password": state.ruleForm.password,
          "roleIds": state.ruleForm.roleIds
        }
        btn_loading.value = true
        addUserApi(obj).then((res: any) => {
          ElMessage({
            type: 'success',
            message: `${res.msg}`,
          })
          formEl.resetFields()
          getList()
          dialogVisible1.value = false
          btn_loading.value = false
        }).catch((res: any) => {
          ElMessage({
            type: 'error',
            message: `${res.msg}`,
          })
          btn_loading.value = false
        })


      } else {
        btn_loading.value = true
        editUserApi(state.ruleForm).then((res: any) => {
          ElMessage({
            type: 'success',
            message: `${res.msg}`,
          })
          formEl.resetFields()
          getList()
          dialogVisible1.value = false
          btn_loading.value = false
        }).catch((res: any) => {
          ElMessage({
            type: 'error',
            message: `${res.msg}`,
          })
          btn_loading.value = false
        })


      }
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  dialogVisible1.value = false
  if (!formEl) return
  formEl.resetFields()
}
const getRoleOptionselectApi_ = async () => {
  await getRoleOptionselectApi().then((res: any) => {
    console.log("角色下拉框", res);
    state.rolesData = res.data
  })
}
getRoleOptionselectApi_()
const getUserInfoApi_ = async (params) => {
  await getUserInfoApi(params).then((res: any) => {
    console.log(res);
    dialogVisible1.value = true
    let arr=[] as any
    res.data.roleIds.forEach(element => {
      arr.push(element)
    });
    state.ruleForm.roleIds=arr
  })
}
</script>
  
<style lang="less" scoped></style>